/**
 * 系统菜单管理 Composable
 * 用于统一处理不同布局下的菜单逻辑
 */
import { ref, watch, onMounted } from "vue";
import { useRoute, onBeforeRouteUpdate } from "vue-router";
import { storeToRefs } from "pinia";
import { useAppSettings } from "@/Stores/appSettings";

/**
 * 菜单配置策略
 * @param {Object} to - 路由对象
 * @param {Object} systemTheme - 主题配置
 * @returns {Object} { menus, currentSubSystem }
 */
const getMenusStrategy = (to, systemTheme) => {
  const hasSubSystem = systemTheme.value.subSystem;
  const layout = systemTheme.value.layout;

  const strategies = {
    horizontal: () => ({
      menus: to.matched[0]?.children || [],
      currentSubSystem: to.path,
    }),
    chapter: () => ({
      menus: to.matched[0]?.children || [],
      currentSubSystem: "",
    }),
    columns: () => ({
      menus: to.matched[hasSubSystem ? 2 : 1]?.children || [],
      currentSubSystem: hasSubSystem ? to.matched[1]?.path || "" : "",
    }),
    default: () => ({
      menus: to.matched[hasSubSystem ? 1 : 0]?.children || [],
      currentSubSystem: hasSubSystem ? to.matched[1]?.path || "" : "",
    }),
    classic: () => ({
      menus: to.matched[hasSubSystem ? 1 : 0]?.children || [],
      currentSubSystem: hasSubSystem ? to.matched[1]?.path || "" : "",
    }),
  };

  return (strategies[layout] || strategies.default)();
};

/**
 * 使用系统菜单
 * @param {Object} options - 配置选项
 * @param {Function} options.onMenuChange - 菜单变化回调
 * @returns {Object} { systemMenus, resetSystemMenus }
 */
export function useSystemMenus(options = {}) {
  const route = useRoute();
  const { appSettings, systemTheme } = storeToRefs(useAppSettings());
  const systemMenus = ref([]);

  const resetSystemMenus = (to = route) => {
    const { menus, currentSubSystem } = getMenusStrategy(to, systemTheme);

    systemMenus.value = menus;
    appSettings.value.currentSubSystem = currentSubSystem;

    // 调用回调
    options.onMenuChange?.({ menus, currentSubSystem });
  };

  // 监听主题和子系统变化
  watch(
    () => [systemTheme.value.subSystem, systemTheme.value.layout],
    () => resetSystemMenus()
  );

  // 路由更新时重置菜单
  onBeforeRouteUpdate((to) => {
    resetSystemMenus(to);
  });

  // 初始化
  onMounted(() => {
    resetSystemMenus();
  });

  return {
    systemMenus,
    resetSystemMenus,
  };
}
